package com.tt.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tt.entity.pojo.MovieInfoPO;
import com.tt.service.MovieInfoService;
import com.tt.util.ConstUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 电影搜索和列表展示（分页）
 * </p>
 *
 * @author sugarttt
 * @version 1.0
 * @since 2023-03-06 14:31:13
 */
@RestController
public class MovieListController {

    private final MovieInfoService movieInfoServiceImpl;

    public MovieListController(MovieInfoService movieInfoServiceImpl) {
        this.movieInfoServiceImpl = movieInfoServiceImpl;
    }

    /**
     * 电影列表
     * @param current
     * @return
     */
    @GetMapping("/list/{page}")
    public ArrayList<MovieInfoPO> getMovieList(@PathVariable("page") Integer current) {
        // current = -1 ,0 ,65535时不会报错，<=0 时认为current=1，current太大时没有数据
        if (current == null) {
            return null;
        }

        Page<MovieInfoPO> page = new Page<>(current, ConstUtil.PAGE_SIZE);
        QueryWrapper<MovieInfoPO> wrapper = new QueryWrapper<>();
        wrapper.orderBy(true,false, Arrays.asList("release_date", "score"));
        Page<MovieInfoPO> result = movieInfoServiceImpl.page(page, wrapper);
        return new ArrayList<>(result.getRecords());
    }

    /**
     * 搜索电影
     * @param val
     * @param current
     * @return
     */
    @GetMapping("/search")
    public ArrayList<MovieInfoPO> searchMovie(String val, Integer current) {
        if (current == null || Strings.isEmpty(val)) {
            return null;
        }

        Page<MovieInfoPO> page = new Page<>(current, ConstUtil.PAGE_SIZE);
        QueryWrapper<MovieInfoPO> wrapper = new QueryWrapper<>();
        wrapper.like("`name`", val)
                .or()
                .like("eng_name", val)
                .orderByDesc("score");

        Page<MovieInfoPO> result = movieInfoServiceImpl.page(page, wrapper);
        return new ArrayList<>(result.getRecords());
    }

    @GetMapping("/type/{type}")
    public ArrayList<MovieInfoPO> getMovieByType(@PathVariable("type") String type, Integer current) {
        if (current == null || Strings.isEmpty(type)) {
            return null;
        }

        return movieInfoServiceImpl.getMovieByType(type, current);
    }
}
